<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use DB;
use App\Http\Requests;
use App\Http\Controllers\Controller;

class CateController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getIndex(Request $request)
    {
        //每页显示条数
       $num=$request->input('num',10);

       // 检测是否提交查询关键字
        if($request->has('keywords')){
            $cates=DB::table('cate')->where('title','like','%'.$request->input('keywords').'%')->paginate($num);
        }else{
            $cates=DB::table('cate')->paginate($num);
        }
         //提取参数 分配到页面中
        $data=$request->except('page');

        //解析模板 分配数据
        return view('Admin.cate.index',['cates'=>$cates,'data'=>$data]);
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function getAdd()
    {
        $cates=DB::table('cate')->get();

        return view('Admin.cate.add',['cates'=>$cates]);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @return \Illuminate\Http\Response
     */
    public function postInsert(Request $request)
    {
        $data=$request->except('_token');

        //判断是否为顶级分类
        if($data['pid']==0)
        {
            $data['path']='0';

        }else{
            $res=DB::table('cate')->where('id',$data['pid'])->first();

            $data['path']=$res->path.','.$data['pid'];

        }

        $res=DB::table('cate')->insert($data);
        if($res)
        {
            return redirect('/admin/cate/index')->with('success','分类添加成功');
        }else{
            return back()->with('error','分类添加失败');
        }
    }

    /**
     * Display the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function show($id)
    {
        //
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function edit($id)
    {
        //
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return \Illuminate\Http\Response
     */
    public function destroy($id)
    {
        //
    }
}
